import { defineStore } from 'pinia'
import { getToken } from '@/utils'
import * as service from './service'
import { filterAsyncRouter } from './premission'
import router, { asyncRouterMap, whitelistRouterMap } from '@/router'
import { storage } from '@/utils'

// useStore 可以是 useUser、useCart 之类的任何东西
// 第一个参数是应用程序中 store 的唯一 id
export const useUserStore = defineStore('user', {
  // other options...
  state () {
    return {
      token: getToken(),
      language: '',
      userInfo: null,
      routes: [],
      menu: null,
      isCollapseState: storage.getItem('IS_COOLPASE_STATE') || false
    }
  },
  actions: {
    async getUseInfo () {
      if (this.userInfo) return

      const [err, data] = await service.getUserinfo()
      if (err || !data) return
      this.userInfo = data
      const menu = handleMenu(data, '')
      const routes = filterAsyncRouter(asyncRouterMap, menu)
      this.routes = routes
      routes.forEach(route => router.addRoute(route))
    }
  },
})

function handleMenu (menu, pid) {
  return menu.reduce((perItem, curItem) => {
    const list = curItem.children ? handleMenu(curItem.children, curItem.id) : []
    return perItem.concat([{ ...curItem, pid }, ...list])
  }, [])
}
